<?php


namespace app\admin\service;



class Token
{


    /**
     * 存储token
     * @param $user_id
     * @param $max_time
     * @param $expire_time
     * @param string $sub
     * @param null $user
     */
    function storeToken($user_id,$expire_time,$sub = "",$user = [])
    {
        $token = hash('sha256',md5($user_id.$sub.time()));
        $id = \app\admin\model\Token::getQuery()->insertGetId([
            'user_id'=>$user_id,
            'create_time'=>time(),
            'expire_time'=>$expire_time+time(),
            'sub'=>$sub,
            'token'=>substr($token,0,32),
            'token_full'=>$token
        ]);
        $data =  [
            'id'=>$id,
            'expire_time'=>$expire_time+time(),
            'user_id'=>$user_id,
            'sub'=>$sub,
            'user'=>$user,
            'token'=>$token
        ];
        $this->storeCache($token,$data,$expire_time);
        return  $data;
    }

    function get($token)
    {
        $key = covertCacheKey(self::class).$token;
        return app('cache')->get($key);
    }

    function delete($token)
    {
        $tokeninfo = $this->get($token);
        if(!!$tokeninfo){
            \app\admin\model\Token::getQuery()->where('id',$tokeninfo['id'])->delete();
        }
        $key = covertCacheKey(self::class).$token;
        app('cache')->delete($key);
    }

    /**
     * 对token加时
     * @param $token
     * @param $expire_time
     * @throws \think\db\exception\DbException
     */
    function renew($token,$expire_time)
    {
        $tokeninfo = $this->get($token);
        if(!!$tokeninfo){
            $tokeninfo['expire_time'] = time()+$expire_time;
            $this->storeCache($token,$tokeninfo,$expire_time);
            \app\admin\model\Token::getQuery()->where('id',$tokeninfo['id'])->update([
                'expire_time'=>time()+$expire_time
            ]);
            return $tokeninfo;
        }
        return $tokeninfo;
    }

    protected function storeCache($token,$data,$expire_time)
    {
        $key = covertCacheKey(self::class).$token;
        app('cache')->set($key,$data,$expire_time);
        return  $data;
    }

}